﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.NET.Core.Service;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Entity.Mailbox;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Service.Maintenance.Dto;
using Admin.Net.InformationPlatform.Entity.Equipment;
using Furion.FriendlyException;
using SjEntityClass;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Numeric;
using System.Net.Mail;
using System.Net;

namespace Admin.Net.InformationPlatform.Service.Mailbox;

/// <summary>
/// 邮箱配置
/// </summary>
[ApiDescriptionSettings(groups: "Mailbox", Name = "邮箱配置", Tag = "邮箱", Order = 200)]
public class MailboxConfigureService : IDynamicApiController, ITransient
{
    private readonly SysUserRoleService _sysUserRoleService;
    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;
    private SmtpClient client = null;

    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// 成品仓库管理模块
    /// </summary>
    /// <param name="db"></param>
    public MailboxConfigureService(ISqlSugarClient db, SysUserRoleService sysUserRoleService)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100TestArea.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);
        _sysUserRoleService = sysUserRoleService;

    }

    /// <summary>
    /// 添加邮箱配置
    /// </summary>
    /// <param name="mailbox"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/AddMailboxConfig")]
    public async Task<string> AddMailboxConfig([FromBody] MailboxConfigure mailbox)
    {
        #region 插入事务
        try
        {
            //开启事务
            _SjDb.Ado.BeginTran();
            int count = await _SjDb.Insertable<MailboxConfigure>(mailbox).ExecuteCommandAsync();

            if (count == 0)
            {
                throw Oops.Oh($"新建任务失败！");
            }
            //提交事务
            _SjDb.Ado.CommitTran();
            return "插入成功";
        }
        catch (Exception e)
        {
            //回滚事务
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }
        #endregion

    }
    /// <summary>
    /// 修改邮箱配置
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/UpdateMailboxConfig")]
    public async Task<string> UpdateMailboxConfig([FromBody] MailboxConfigure input)
    {
        //提交
        try
        {
            _SjDb.Ado.BeginTran();
            int count = await _SjDb.Updateable<MailboxConfigure>()
                .SetColumns(a => a.FromEmail == input.FromEmail)
                .SetColumns(a => a.SmtpPort == input.SmtpPort)
                .SetColumns(a => a.SmtpServe == input.SmtpServe)
                .SetColumns(a => a.ExcelPassWord == input.ExcelPassWord)
                .Where(a => a.UserName == input.UserName)
                .ExecuteCommandAsync();

            if (count == 0)
            {
                throw Oops.Oh("修改失败！");
            }
            _SjDb.Ado.CommitTran();
            return "修改成功！";
        }
        catch (Exception e)
        {
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }
    }

    /// <summary>
    /// 根据登录账号查询邮箱配置
    /// </summary>
    /// <param name="userName"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/GetMailboxConfig")]
    public async Task<List<MailboxConfigure>> GetMailboxConfig(string userName) {

        var output = await _SjDb.Queryable<MailboxConfigure>()
      .WhereIF(!string.IsNullOrEmpty(userName), (l) => (l.UserName.Contains(userName)))//账号
      .ToListAsync();

        return output;
    }

    /// <summary>
    ///发送邮件接口
    /// </summary>
    /// <param name="mail"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/TimeTaskEmail")]
    public string TimeTaskEmail(Entity.Mailbox.MailMessage mail)
    {



        if (client == null)
        {
            client = new SmtpClient(mail.Host, mail.Ip);
        }


        client.EnableSsl = mail.EnableSsl;
        client.UseDefaultCredentials = mail.UseDefaultCredentials;
        client.Credentials = new NetworkCredential(mail.FromEmail, mail.PassWord);
        client.DeliveryMethod = SmtpDeliveryMethod.Network; // 设置邮件的传送方式为网络传送
        client.Timeout = 10000; // 设置超时时间，单位为毫秒

        System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(mail.FromEmail, mail.ToEmail, mail.Subject, mail.Body);

        if (mail.FileUrl != null && mail.FileUrl.Count > 0) {
            foreach (string item in mail.FileUrl)
            {
                System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(item);
                mailMessage.Attachments.Add(attachment);
            }
        }


        try
        {
            client.Send(mailMessage);
            Console.WriteLine("Email sent successfully.");
            return "发送成功";
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to send email. Error message: " + ex.Message);
            return "发送失败";
        }


    }

    /// <summary>
    /// 添加定时任务配置
    /// </summary>
    /// <param name="config"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/AddMailboxTaskConfig")]
    public async Task<string> AddMailboxTaskConfig([FromBody] MailboxTaskConfig config) {

        try
        {
            //开启事务
            _SjDb.Ado.BeginTran();
            int count = await _SjDb.Insertable<MailboxTaskConfig>(config).ExecuteCommandAsync();

            if (count == 0)
            {
                throw Oops.Oh($"新建任务失败！");
            }
            //提交事务
            _SjDb.Ado.CommitTran();
            return "插入成功";
        }
        catch (Exception e)
        {
            //回滚事务
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }
    }

    /// <summary>
    /// 查询定时任务配置
    /// </summary>
    /// <param name="TaskName"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/SelectMailboxConfigure")]
    public async Task<List<MailboxTaskConfig>> SelectMailboxConfigure(string TaskName) {

        var output = await _SjDb.Queryable<MailboxTaskConfig>()
       .WhereIF(!string.IsNullOrEmpty(TaskName), (l) => (l.TaskName.Contains(TaskName)))//账号
       .Where(a =>a.TaskState !=1)
       .ToListAsync();

        return output;
    }

    /// <summary>
    /// 修改定时任务配置
    /// </summary>
    /// <param name="mailbox"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/UpdateMailboxConfigure")]
    public async Task<string> UpdateMailboxConfigure(MailboxTaskConfig mailbox) {

        //提交
        try
        {
            _SjDb.Ado.BeginTran();
            int count = await _SjDb.Updateable<MailboxTaskConfig>()
                .SetColumns(a => a.TaskName == mailbox.TaskName)
                .SetColumns(a => a.TaskRemark == mailbox.TaskRemark)
                .SetColumns(a => a.TaskTime == mailbox.TaskTime)  
                .SetColumns(a=> a.TaskState == mailbox.TaskState)
                .Where(a => a.Id == mailbox.Id)
                .ExecuteCommandAsync();

            if (count == 0)
            {
                throw Oops.Oh("修改失败！");
            }
            _SjDb.Ado.CommitTran();
            return "修改成功！";
        }
        catch (Exception e)
        {
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }


    }

    /// <summary>
    /// 删除定时任务
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    [HttpPost("/Mailbox/DeleteMailboxConfigure")]
    public async Task<string> DeleteMailboxConfigure(int Id) {

        //提交
        try
        {
            _SjDb.Ado.BeginTran();
            int count = await _SjDb.Updateable<MailboxTaskConfig>()
                .SetColumns(a => a.TaskState == 1)
                .Where(a => a.Id == Id)
                .ExecuteCommandAsync();

            if (count == 0)
            {
                throw Oops.Oh("删除失败！");
            }
            _SjDb.Ado.CommitTran();
            return "删除成功！";
        }
        catch (Exception e)
        {
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }

    }

}
